package com.woniu.tmsvehicle.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {
    public static final String REFRESH_QUEUE_NAME = "refresh_queue";
    public static final String REFRESH_DIRECT_EXCHANGE_NAME = "refresh_direct_exchange";
    public static final String REFRESH_ROUTING_KEY = "refresh_route";





    public static final String DEAD_EXCHANGE_NAME = "dead_exchange";
    public static final String DEAD_QUEUE_NAME = "dead_queue";
    public static final String DEAD_ROUTING_KEY = "dead_route";

    public static final int TTL = 10 * 1000;
    public static final int MAX_LENGTH = 10;
    // drop-head：删除队列头  会成为死信
    // reject-publish：直接拒绝消息，消息不会成为死信
    // reject-publish-dlx：直接拒绝，会成为死信
    public static final String OVERFLOW_MODE = "reject-publish";

    // 创建消息队列
    @Bean
    public Queue refreshQueue(){
        Map<String, Object> args = new HashMap<>();
        // 设置死信交换机
        args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        // 设置死信路由
        args.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);
        // 超时时间
        args.put("x-message-ttl", TTL);
        // 设置队列长度
        args.put("x-max-length", MAX_LENGTH);
        // 设置溢出处理方式
        args.put("x-overflow", OVERFLOW_MODE);
        //
        return new Queue(REFRESH_QUEUE_NAME, true, false,false, args);
    }



    // 交换机
    @Bean
    public DirectExchange refreshDirectExchange(){
        return new DirectExchange(REFRESH_DIRECT_EXCHANGE_NAME);
    }
    // 绑定
    @Bean
    public Binding bindingTestQueueToTestDirectExchange(){
        return BindingBuilder.bind(refreshQueue()).to(refreshDirectExchange()).with(REFRESH_ROUTING_KEY);
    }

    /**
     * 死信消息队列、交换机
     */
    @Bean
    public Queue deadQueue(){
        return new Queue(DEAD_QUEUE_NAME);
    }
    @Bean
    public DirectExchange deadDirectExchange(){
        return new DirectExchange(DEAD_EXCHANGE_NAME);
    }
    @Bean
    public Binding bindingDeadQueueToDeadDirectExchange(){
        return BindingBuilder.bind(deadQueue()).to(deadDirectExchange()).with(DEAD_ROUTING_KEY);
    }
}
